package com.tfswue.hql.controller;

import com.tfswue.hql.common.Result;
import com.tfswue.hql.entity.User;
import com.tfswue.hql.exception.BusinessException;
import com.tfswue.hql.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(400, "用户ID不能为空或小于等于0");
        }
        User user = userService.getUserById(id);
        if (user == null) {
            return Result.notFound("用户不存在");
        }
        return Result.success(user);
    }
    
    @GetMapping
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return Result.success(users);
    }
    
    @PostMapping
    public Result<User> createUser(@RequestBody User user) {
        if (user == null || user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new BusinessException(400, "用户名不能为空");
        }
        User createdUser = userService.createUser(user);
        return Result.success("用户创建成功", createdUser);
    }
    
    @PutMapping("/{id}")
    public Result<User> updateUser(@PathVariable Long id, @RequestBody User user) {
        if (id == null || id <= 0) {
            throw new BusinessException(400, "用户ID不能为空或小于等于0");
        }
        if (user == null || user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new BusinessException(400, "用户名不能为空");
        }
        user.setId(id);
        User updatedUser = userService.updateUser(user);
        if (updatedUser == null) {
            return Result.notFound("用户不存在");
        }
        return Result.success("用户更新成功", updatedUser);
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(400, "用户ID不能为空或小于等于0");
        }
        boolean deleted = userService.deleteUser(id);
        if (!deleted) {
            return Result.notFound("用户不存在");
        }
        return Result.success();
    }
}
